package com.ysd.lis.service.bac.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.bac.BacGermDict;
import com.ysd.lis.entity.bac.BacInstrGermDict;
import com.ysd.lis.mapper.bac.BacGermDictMapper;
import com.ysd.lis.request.GremDictDto;
import com.ysd.lis.request.Params;
import com.ysd.lis.request.bac.AntibioticsDictParam;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.bac.BacGermDictService;
import com.ysd.util.ToolsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 微生物基础字典 服务实现类
 * </p>
 *
 * @author HuaiXing
 * @since 2024-01-11
 */
@Service
public class BacGermDictServiceImpl extends ServiceImpl<BacGermDictMapper, BacGermDict> implements BacGermDictService {

    @Autowired
    BacGermDictMapper bacGermDictMapper;

    @Override
    public Result findGermList(Params params) {
        Page<BacGermDict> page = new Page<>();
        page.setCurrent(params.getPageIndex());
        page.setSize(params.getPageSize());


        LambdaQueryWrapper<BacGermDict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BacGermDict::getDelFlag, 0);
        if (!StringUtils.isEmpty(params.getSearchValue())) {
            queryWrapper.and(wrapper -> wrapper.like(BacGermDict::getGermNa, params.getSearchValue()).or().like(BacGermDict::getGermNo, params.getSearchValue()));
        }
        if (!BeanUtil.isEmpty(params.getGermType())) {
            queryWrapper.eq(BacGermDict::getGermType, params.getGermType());
        }
        if (!BeanUtil.isEmpty(params.getIsCommon()) && params.getIsCommon().equals(1)) {
            queryWrapper.eq(BacGermDict::getIsCommon, 1);
        }
        if (!BeanUtil.isEmpty(params.getIsCommon()) && params.getIsCommon().equals(0)) {
            queryWrapper.eq(BacGermDict::getIsCommon, 0);
        }
        Page<BacGermDict> bacGermDictPage = bacGermDictMapper.selectPage(page, queryWrapper);
        List<BacGermDict> records = bacGermDictPage.getRecords();
        if(ToolsUtils.isNotEmpty(records)){
            //获取字典 并且塞进数据
            List<Map<String, Object>> genusCodeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("genusCode").getData();
            List<Map<String, Object>> speciesGroupList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("speciesGroup").getData();
            List<Map<String, Object>> genusList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("genus").getData();
            List<Map<String, Object>> genusGroupList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("genusGroup").getData();
            List<Map<String, Object>> familyCodeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("familyCode").getData();
            List<Map<String, Object>> orgOrderList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("orgOrder").getData();
            List<Map<String, Object>> germTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("germType").getData();
            List<Map<String, Object>> serumGroupList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("serumGroup").getData();
            List<Map<String, Object>> phylumCodeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("phylumCode").getData();
            List<Map<String, Object>> orgKingdomList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("orgKingdom").getData();


            for(BacGermDict germDict : records){
                if (StringUtils.isNotBlank(germDict.getGenusCode()) && CollectionUtils.isNotEmpty(genusCodeList)) {
                    genusCodeList.stream().filter(a -> a.get("code").equals(germDict.getGenusCode())).findFirst().ifPresent(stringObjectMap -> germDict.setGenusCodeNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(germDict.getSpeciesGroup()) && CollectionUtils.isNotEmpty(speciesGroupList)) {
                    speciesGroupList.stream().filter(a -> a.get("code").equals(germDict.getSpeciesGroup())).findFirst().ifPresent(stringObjectMap -> germDict.setSpeciesGroupNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(germDict.getGenus()) && CollectionUtils.isNotEmpty(genusList)) {
                    genusList.stream().filter(a -> a.get("code").equals(germDict.getGenus())).findFirst().ifPresent(stringObjectMap -> germDict.setGenusNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(germDict.getGenusGroup()) && CollectionUtils.isNotEmpty(genusGroupList)) {
                    genusGroupList.stream().filter(a -> a.get("code").equals(germDict.getGenusGroup())).findFirst().ifPresent(stringObjectMap -> germDict.setGenusGroupNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(germDict.getGermType()) && CollectionUtils.isNotEmpty(germTypeList)) {
                    germTypeList.stream().filter(a -> a.get("code").equals(germDict.getGermType())).findFirst().ifPresent(stringObjectMap -> germDict.setGermTypeNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(germDict.getPhylumCode()) && CollectionUtils.isNotEmpty(phylumCodeList)) {
                    phylumCodeList.stream().filter(a -> a.get("code").equals(germDict.getPhylumCode())).findFirst().ifPresent(stringObjectMap -> germDict.setPhylumCodeNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(germDict.getOrgKingdom()) && CollectionUtils.isNotEmpty(orgKingdomList)) {
                    orgKingdomList.stream().filter(a -> a.get("code").equals(germDict.getOrgKingdom())).findFirst().ifPresent(stringObjectMap -> germDict.setOrgKingdomNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(germDict.getSerumGroup()) && CollectionUtils.isNotEmpty(serumGroupList)) {
                    serumGroupList.stream().filter(a -> a.get("code").equals(germDict.getSerumGroup())).findFirst().ifPresent(stringObjectMap -> germDict.setSerumGroupNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(germDict.getOrgOrder()) && CollectionUtils.isNotEmpty(orgOrderList)) {
                    orgOrderList.stream().filter(a -> a.get("code").equals(germDict.getOrgOrder())).findFirst().ifPresent(stringObjectMap -> germDict.setOrgOrderNa((String) stringObjectMap.get("name")));
                }
                if (StringUtils.isNotBlank(germDict.getFamilyCode()) && CollectionUtils.isNotEmpty(familyCodeList)) {
                    familyCodeList.stream().filter(a -> a.get("code").equals(germDict.getFamilyCode())).findFirst().ifPresent(stringObjectMap -> germDict.setFamilyCodeNa((String) stringObjectMap.get("name")));
                }

            }
        }
        return Result.succ(1, "查询成功", bacGermDictPage);
    }
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Override
    public Result getGermsByParams(Params params) {
        LambdaQueryWrapper<BacGermDict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BacGermDict::getDelFlag, 0);
        if (!StringUtils.isEmpty(params.getSearchValue())) {
            queryWrapper.and(wrapper -> wrapper.like(BacGermDict::getGermNa, params.getSearchValue()).or().like(BacGermDict::getGermNo, params.getSearchValue()));
        }
        if (StringUtils.isNotBlank(params.getSeachValue())) {
            queryWrapper.and(wrapper -> wrapper.like(BacGermDict::getGermNa, params.getSeachValue()).or().like(BacGermDict::getGermNo, params.getSeachValue()));
        }
        if (!BeanUtil.isEmpty(params.getGermType())) {
            queryWrapper.eq(BacGermDict::getGermType, params.getGermType());
        }
        if (!BeanUtil.isEmpty(params.getIsCommon()) && params.getIsCommon().equals(1)) {
            queryWrapper.eq(BacGermDict::getIsCommon, 1);
        }
        if (!BeanUtil.isEmpty(params.getIsCommon()) && params.getIsCommon().equals(0)) {
            queryWrapper.eq(BacGermDict::getIsCommon, 0);
        }
        if (StringUtils.isNotEmpty(params.getGenus())){
            queryWrapper.eq(BacGermDict::getGenus, params.getGenus());
        }
        List<BacGermDict> bacGermDictPage = bacGermDictMapper.selectList(queryWrapper);
        return Result.succ(1, "查询成功", bacGermDictPage);
    }

    @Override
    public Result addGermDict(BacGermDict bacGermDict) {

        int i = bacGermDictMapper.insert(bacGermDict);
        if (i > 0) {
            return Result.succ(1, "新增成功", "");
        } else {
            return Result.fail("添加微生物失败");
        }
    }

    @Override
    public Result updateGermDict(BacGermDict bacGermDict) {

        int i = bacGermDictMapper.updateById(bacGermDict);
        if (i > 0) {
            return Result.succ(1, "修改成功", "");
        } else {
            return Result.fail("修改微生物失败");
        }
    }

    @Override
    public Result batchDeleteGermDict(GremDictDto vo) {
        List<BacGermDict> bacGermDictList = vo.getBacGermDictList();

        List<String> ids = bacGermDictList.stream().map(BacGermDict::getId).collect(Collectors.toList());

        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }

    }

    @Override
    public Result findGermDictByInstrId(AntibioticsDictParam dictParam) {
        MPJLambdaWrapper<BacGermDict> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(BacGermDict.class).eq(BacGermDict::getDelFlag, 0);
        if (StrUtil.isNotEmpty(dictParam.getKeyWords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(BacGermDict::getGermNo, dictParam.getKeyWords()).or().like(BacGermDict::getGermNa, dictParam.getKeyWords()));
        }
        if (StrUtil.isNotEmpty(dictParam.getInstrCode())) {
            StringBuffer existsSql = new StringBuffer("SELECT 1 FROM BAC_INSTR_GERM_DICT t2 WHERE t.GERM_NO = t2.GERM_NO AND t2.INSTR_CODE = '" + dictParam.getInstrCode() + "' ");
            lambdaQueryWrapper.notExists(existsSql.toString());
        }
        List<BacGermDict> bacGermDicts = bacGermDictMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功！", bacGermDicts);
    }

    @Override
    public Result findInstrGermDictsByInstrId(AntibioticsDictParam dictParam) {
        Assert.hasText(dictParam.getInstrCode(), "id must not be empty");
        MPJLambdaWrapper<BacGermDict> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper
                .selectAll(BacGermDict.class)
                .selectAs(BacInstrGermDict::getId, BacGermDict::getInstrAntibDictId)
                .selectAs(BacInstrGermDict::getInputGermNo, BacGermDict::getInputGermNo)
                .selectAs(BacInstrGermDict::getInputGermNa, BacGermDict::getInputGermNa)
                .leftJoin(BacInstrGermDict.class, BacInstrGermDict::getGermNo, BacGermDict::getGermNo)
                .eq(BacInstrGermDict::getInstrCode, dictParam.getInstrCode()).eq(BacGermDict::getDelFlag, 0);
        if (StrUtil.isNotEmpty(dictParam.getKeyWords())) {
            mpjLambdaWrapper.and(wrapper -> wrapper.like(BacGermDict::getGermNo, dictParam.getKeyWords()).or().like(BacGermDict::getGermNa, dictParam.getKeyWords()));
        }
        List<BacGermDict> bacGermDicts = bacGermDictMapper.selectList(mpjLambdaWrapper);
        return Result.succ(1, "查询成功", bacGermDicts);
    }

    @Override
    public Result batchUpdateGermDict(GremDictDto vo) {
        List<BacGermDict> bacGermDictList = vo.getBacGermDictList();
        //批量插入
        boolean b = this.saveOrUpdateBatch(bacGermDictList);
        if (b) {
            return Result.succ(1, "批量修改成功", null);
        } else {
            return Result.fail(400, "批量修改失败", null);
        }
    }

    @Override
    public Result findPageGermDictByInstrId(AntibioticsDictParam dictParam) {
        Page<BacGermDict> page = new Page<>();
        page.setCurrent(dictParam.getPageIndex());
        page.setSize(dictParam.getPageSize());

        MPJLambdaWrapper<BacGermDict> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(BacGermDict.class).eq(BacGermDict::getDelFlag, 0);
        if (StrUtil.isNotEmpty(dictParam.getKeyWords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(BacGermDict::getGermNo, dictParam.getKeyWords()).or().like(BacGermDict::getGermNa, dictParam.getKeyWords()));
        }
        if (StrUtil.isNotEmpty(dictParam.getInstrCode())) {
            StringBuffer existsSql = new StringBuffer("SELECT 1 FROM BAC_INSTR_GERM_DICT t2 WHERE t.GERM_NO = t2.GERM_NO AND t2.INSTR_CODE = '" + dictParam.getInstrCode() + "' ");
            lambdaQueryWrapper.notExists(existsSql.toString());
        }
        Page<BacGermDict> bacGermDicts = bacGermDictMapper.selectPage(page,lambdaQueryWrapper);
        return Result.succ(1, "查询成功！", bacGermDicts);
    }
}
